import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { Condition } from '../../models';
import { EngineService } from '../engines/services/engine.service';
import { compareDataField, compareFns, compareOperators } from '../tools/condition-tool';

@Injectable({
  providedIn: 'root'
})
export class ConditionService {

  private _conditions: Condition[] = [];

  get conditions() {
    return this._conditions;
  }

  set conditions(data: Condition[]) {
    this._conditions = data;
  }

  get splitRegx() {
    const regxSr = compareOperators.join('|');
    return new RegExp(`${regxSr}`, 'g');
  }

  constructor(
    private engineService: EngineService
  ) {
    this.onComponentFieldChange();
  }

  fieldChange$: Subject<Condition[]> = new Subject<Condition[]>();

  fieldValueChange(dataModel: any) {
    if (this.conditions && this.conditions.length) {
      const result = [];
      this.conditions.forEach(condition => {
        const compareResult = this.checkCondition(dataModel, condition);
        condition.result = compareResult;
        result.push(condition);
      });
      this.fieldChange$.next(result);
    }
  }

  checkCondition(dataModal: { [key: string]: any }, condition: Condition) {
    return compareDataField(dataModal, condition);
  }

  onComponentFieldChange() {
    this.engineService.dataModelChange$.subscribe(data => {
      this.fieldValueChange(data.dataModel);
    });
  }

  clear() {
    this.conditions = [];
  }

}
